﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncDownloadFile
{
    public partial class AsyDownloadFile : Form
    {
        /// <summary>
        ///文件大小
        /// </summary>
        public int DownloadSize = 0; 
        /// <summary>
        /// 文件路径
        /// </summary>
        public string downloadPath = null;
        long totalSize = 0;
        const int BufferSize = 2048;
        byte[] BufferRead = new byte[BufferSize];
        FileStream filestream = null;
        HttpWebResponse myWebResponse = null;
        //Thread urd;
        public AsyDownloadFile()
        {
            InitializeComponent();
			string url = @"https://dl.tvcdn.de/download/TeamViewer_Setup.exe";
			//string url = @"http://sc.chinaz.com/tupian/180711559982.htm";
			txtUrl.Text = url;
			this.btnPause.Enabled = false;
			GetTotalSize();
			downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + Path.GetFileName(this.txtUrl.Text.Trim());
			if (File.Exists(downloadPath))
			{
				FileInfo fileInfo = new FileInfo(downloadPath);
				DownloadSize = (int)fileInfo.Length;
				try
				{
					progressBar1.Value = (int)((float)DownloadSize / (float)totalSize * 100);
				}
				catch (Exception)
				{
					MessageBox.Show("连接被中止！请检查外网是否可用或者网络是否加密！");
				}
			}
		}
        private void AsyncDownloadFile_Load(object sender, EventArgs e)
        {
            //urd = new Thread(new ThreadStart(this.dd));
            //urd.Start();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        //void dd()
        //{
        //        this.BeginInvoke(new Action(() => {
                   
        //        }));          
        //}     
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                backgroundWorker1.RunWorkerAsync();
                filestream = new FileStream(downloadPath, FileMode.OpenOrCreate);
                filestream.Seek(DownloadSize, SeekOrigin.Begin);
                this.btnStart.Enabled = false;
                this.btnPause.Enabled = true;
            }
            else
            {
                MessageBox.Show("正在执行操作，请稍后");
            }
        }
        /// <summary>
        /// 获得文件总大小
        /// </summary>
        private void GetTotalSize()
        {
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text.Trim());
                HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                totalSize = response.ContentLength;
                response.Close();
            }
            catch (Exception e)
            {
                e.ToString();
				MessageBox.Show(e.ToString());
            }
           
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy && backgroundWorker1.WorkerSupportsCancellation == true)
            {
                backgroundWorker1.CancelAsync();//取消下载操作
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgworker = sender as BackgroundWorker;
            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text.Trim());
                if (DownloadSize != 0)
                {
                    myHttpWebRequest.AddRange(DownloadSize);
                }
                myWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                Stream responseStream = myWebResponse.GetResponseStream();
                int readSize = 0;
                while (true)
                {
                    if (backgroundWorker1.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    readSize = responseStream.Read(BufferRead, 0, BufferRead.Length);
                    if (readSize > 0)
                    {
                        DownloadSize += readSize;
                        int percentComplete = (int)((float)DownloadSize / (float)totalSize * 100);
                        filestream.Write(BufferRead, 0, readSize);
                        backgroundWorker1.ReportProgress(percentComplete);
                    }
                    else { break; }
                }
            }
            catch
            {
                MessageBox.Show("连接被中止！请检查外网是否可用或者网络是否加密！");
            }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                XtraMessageBox.Show(e.Error.Message);
                myWebResponse.Close();
            }
            else if (e.Cancelled)
            {
                MessageBox.Show(string.Format("下载暂停，下载文件地址为{0},下载大小为{1}", downloadPath, DownloadSize));
                myWebResponse.Close();
                filestream.Close();
                this.btnStart.Enabled = true;
                this.btnPause.Enabled = false;
            }
            else
            {
                MessageBox.Show("下载完成");
                myWebResponse.Close();
                filestream.Close();
                this.btnStart.Enabled = true;
                this.btnPause.Enabled = false;
            }
        }
    }
}
